<?php


namespace App\Admin\Forms;


use App\Models\AdminConfig;
use Dcat\Admin\Layout\Content;
use Dcat\Admin\Widgets\Form;
use Illuminate\Support\Facades\Storage;
use Symfony\Component\HttpFoundation\Response;

class Config extends Form
{
    protected $group_id = 0;

    public function index(Content $content) {
        $content->withError('Title', 'messages..');
        die();
        return $content;
    }
    /**
     * Handle the form request.
     *
     * @param array $input
     *
     * @return Response
     */
    public function handle(array $input) {

        foreach ($input as $k => $v) {
            AdminConfig::where("name", $k)->limit(1)->update(['value' => $v]);
        }
        $fields = AdminConfig::orderBy("sort", "asc")
            ->orderBy("id", "asc")->get();
        $datas = [];
        foreach ($fields as $k => $v) {
            if (empty($v->env) || trim($v->env) == "") {
                continue;
            }
            $datas[strtoupper($v->env)] = $v->value;
        }
        if (!empty($datas)) {
            $this->modifyEnv($datas);
        }

        return $this->success('保存成功.', '/coConfig');
    }

    /**
     * Build a form here.
     */
    public function form() {

        $groups = AdminConfig::getConfigGroup();
        foreach ($groups as $k => $group) {
            if($k =='config'){
                $this->group_id = $k;
                $this->tab($group, function (Form $form) {
                    $fields = AdminConfig::where("group", 'config')
                        ->orderBy("sort", "asc")->orderBy("id", "asc")->get();
                    foreach ($fields as $field) {
                        $options = [];
                        $arr = explode(",", str_ireplace("\r\n", ",", $field->options));
                        if (gettype($arr) == 'string') {
                            $arr = [$arr];
                        }

                        foreach ($arr as $key => $val) {
                            $arr2 = explode(":", $val);
                            if (gettype($arr2) == "array" && count($arr2) > 1) {
                                $options[$arr2[0]] = $arr2[1];
                            }
                        }
                        $holder = empty($field->placeholder) ? "请输入" . $field->title : $field->placeholder;
                        switch ($field->type) {
                            case 'select':
                                $form->select($field->name, $field->title)
                                    ->placeholder($holder)
                                    ->options($options)->value($field->value);
                                break;
                            case 'radio':
                                $form->radio($field->name, $field->title)
                                    ->placeholder($holder)
                                    ->help($field->help)
                                    ->options($options)->value($field->value);
                                break;
                            case 'checkbox':
                                $form->checkbox($field->name, $field->title)
                                    ->placeholder($holder)
                                    ->help($field->help)
                                    ->options($options)->value($field->value);
                                break;

                            case 'cert':
                                $form->file($field->name, $field->title)
                                    ->placeholder($holder)
                                    ->help($field->help)
                                    ->disk('cert')
                                    ->value(storage_path('cert') . $field->value)
                                ;
                                break;
                            case 'date':
                                $form->date($field->name, $field->title)
                                    ->placeholder($holder)
                                    ->help($field->help)
                                    ->value($field->value);
                                break;
                            case 'datetime':
                                $form->datetime($field->name, $field->title)
                                    ->placeholder($holder)
                                    ->value($field->value);
                                break;
                            case 'image':

                                $url = Storage::disk(env("FILESYSTEM_DRIVER"))->url($field->value);
                                $form->image($field->name, $field->title)
                                    ->accept('jpg,png,gif,jpeg,bmp,jpg', 'image/*')
                                    ->placeholder($holder)
                                    ->url("upload")
                                    ->value($url);
                                break;
                            case 'input':
                            case 'number':
                                if (!empty($field->help) && trim($field->help) != '') {
                                    $form->text($field->name, $field->title)
                                        ->help($field->help)
                                        ->placeholder($holder)
                                        ->value($field->value);
                                } else {
                                    $form->text($field->name, $field->title)
                                        ->placeholder($holder)
                                        ->value($field->value);
                                }
                                break;

                            case 'textarea':
                                if (!empty($field->help) && trim($field->help) != '') {
                                    $form->textarea($field->name, $field->title)
                                        ->help($field->help)
                                        ->placeholder($holder)
                                        ->value($field->value);
                                } else {
                                    $form->textarea($field->name, $field->title)
                                        ->placeholder($holder)
                                        ->value($field->value);
                                }
                            default:
                                # code...
                                break;
                        }
                    }
                });
            }
        }

    }

    /**
     * The data of the form.
     *
     * @return array
     */
    public function default() {
        return [
            'name' => 'John Doe',
            'email' => 'John.Doe@gmail.com',
        ];
    }
    protected function modifyEnv(array $data) {
        $envPath = base_path() . DIRECTORY_SEPARATOR . '.env';

        $contentArray = collect(file($envPath, FILE_IGNORE_NEW_LINES));

        $contentArray->transform(function ($item) use ($data) {
            foreach ($data as $key => $value) {
                if (str_contains($item, $key)) {
                    return $key . '=' . $value;
                }
            }
            return $item;
        });
        $content = implode($contentArray->toArray(), "\n");
        \File::put($envPath, $content);
    }
}
